import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Loading from '../../components/loading/Loading';
import Table from '../../components/table/Table';
import * as tableActions from '../../actions/tableActions';
import CONST from '../../commons/const';
import styles from './main.scss';

class Main extends React.Component {
  constructor(props) {
    super(props);
    this.displayName = 'Main';
    this.url = `${CONST.BASE_API}/data/latest`;
  }

  componentWillMount() {
    this.props.testAction('hhaha');
    this.props.fetchDatas(this.url);
  }

  render() {
    const { tableDatas } = this.props;
    const content = (loading) => {
      if (loading) {
        return <Loading />;
      }
      return <Table datas={tableDatas} />;
    };
    return (
      <div className={styles.wrap}>
        {content(this.props.isLoading)}
      </div>
    );
  }
}

Main.propTypes = {
  tableDatas: React.PropTypes.any,
  testAction: React.PropTypes.func,
  fetchDatas: React.PropTypes.func,
  isLoading: React.PropTypes.bool,
};

//  对从 redux 的 store 来的 state 做过滤
const mapStateToProps = state => ({
  tableDatas: state.table.tableDatas,
  isLoading: state.table.isLoading,
});

const mapDispatchToProps = (dispatch) => bindActionCreators(tableActions, dispatch);

// 用 connenct 包装 container
// 注入 dispatch 和全局 state
// action 调用 dispatch 的话， 要加 thunk
export default connect(mapStateToProps, mapDispatchToProps)(Main);
